import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;

public class GameWin extends JFrame {

    //游戏状态 0.开始 1。游戏中 2.暂停 3.失败 4.通关 5.失败后重启 6.下一关
    public static int state = 0;
    //分数
    public int score = 0;
    //定义双缓存的图片
    Image offScreenImage = null;
    //窗口宽高
    int winWidth = 800;
    int winHeight = 600;

    //蛇头对象
    HeadObj headObj;
    //蛇身的集合
    public List<BodyObj> bodyObjList = new ArrayList<>();

    //食物列表（支持多个食物）
    public List<FoodObj> foodList = new ArrayList<>();

    public void launch(){
        //先初始化蛇头
        headObj = new HeadObj(GameUtils.rightImg, 60, 570, this);

        //再初始化蛇身
        bodyObjList.add(new BodyObj(GameUtils.bodyImg, 30, 570, this));
        bodyObjList.add(new BodyObj(GameUtils.bodyImg, 0, 570, this));

        //最后初始化食物
        initFood();

        //设置窗口是否可见
        this.setVisible(true);
        //设置窗口的大小
        this.setSize(winWidth, winHeight);
        //设置窗口的位置在屏幕上居中
        this.setLocationRelativeTo(null);
        //设置窗口的标题
        this.setTitle("我的贪吃蛇 - 第" + GameUtils.level + "关");

        //键盘事件
        this.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_SPACE){
                    switch (state){
                        //未开始
                        case 0:
                            state = 1;
                            break;
                        case 1:
                            //游戏中
                            state = 2;
                            repaint();
                            break;
                        case 2:
                            //游戏暂停
                            state = 1;
                            break;
                        case 3:
                            //失败后重新开始
                            state = 5;
                            break;
                        case 4:
                            //下一关
                            state = 6;
                            break;
                        default:
                            break;
                    }
                }
            }
        });

        this.setFocusable(true);
        this.requestFocusInWindow();

        while (true){
            if (state == 1){
                repaint();
            }
            //失败重启
            if (state == 5){
                state = 0;
                resetGame();
            }
            //通关下一关
            if (state == 6 && GameUtils.level < GameUtils.LEVEL_TARGETS.length){
                state = 1;
                GameUtils.level++;
                resetGame();
            }
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public void initFood() {
        foodList.clear();

        // ========== 修复开始：确保食物正确初始化 ==========
        if (GameUtils.level == 4) {
            // 第四关：生成三个食物，确保每个都有正确的frame引用
            FoodObj foodGenerator = new FoodObj();
            foodGenerator.frame = this;

            for (int i = 0; i < 3; i++) {
                FoodObj newFood = foodGenerator.getFoodForLevel4(this);
                foodList.add(newFood);
            }
        } else {
            // 其他关卡：单个食物
            FoodObj foodGenerator = new FoodObj();
            foodGenerator.frame = this;
            foodList.add(foodGenerator.getFood());
        }
        // ========== 修复结束 ==========
    }

    private int getCurrentLevelTarget() {
        if (GameUtils.level <= GameUtils.LEVEL_TARGETS.length) {
            return GameUtils.LEVEL_TARGETS[GameUtils.level - 1];
        }
        return 15;
    }

    @Override
    public void paint(Graphics g){
        //初始化双缓存图片
        if (offScreenImage == null){
            offScreenImage = this.createImage(winWidth,winHeight);
        }
        //获取图片对应的graphics对象
        Graphics gImage = offScreenImage.getGraphics();
        //灰色背景
        gImage.setColor(GameUtils.COLOR_BACKGROUND);
        gImage.fillRect(0,0,winWidth,winHeight);
        //网格线
        gImage.setColor(GameUtils.COLOR_GRID);
        //横线
        for (int i = 0; i < 20; i++) {
            //横线
            gImage.drawLine(0,i * 30,600,i * 30);//横线
            //竖线
            gImage.drawLine(i*30,0,i * 30,600);//竖线
        }
        //绘制蛇身
        for (int i = bodyObjList.size() - 1; i >= 0; i--) {
            bodyObjList.get(i).paintSelf(gImage);
        }
        //绘制蛇头
        headObj.paintSelf(gImage);
        //食物绘制
        for (FoodObj food : foodList) {
            if (food != null) {
                food.paintSelf(gImage);
            }
        }
        //关卡
        GameUtils.drawWord(gImage,"第" + GameUtils.level + "关",GameUtils.COLOR_LEVEL_TEXT,40,650,260);
        //分数绘制
        int currentTarget = getCurrentLevelTarget();
        String scoreText;
        if (GameUtils.level == 5) {
            scoreText = score + " 分 - 无尽模式";
        } else {
            scoreText = score + " / " + currentTarget + " 分";
        }
        GameUtils.drawWord(gImage, scoreText, GameUtils.COLOR_SCORE_TEXT, 35, 630, 330);

        //进度提示
        if (GameUtils.level != 5) {
            GameUtils.drawWord(gImage,"目标:吃" + currentTarget + "个食物",Color.DARK_GRAY,20,630,370);
        }
        //绘制提示语
        gImage.setColor(Color.gray);
        prompt(gImage);
        //将双缓存图片绘制到主窗口中
        g.drawImage(offScreenImage,0,0,null);
    }

    //绘制提示语
    void prompt(Graphics g){
        //未开始
        if (state == 0){
            g.fillRect(120,240,400,70);
            GameUtils.drawWord(g,"按下空格开始游戏",GameUtils.COLOR_START_TEXT,35,150,290);
        }
        //暂停
        if (state == 2){
            g.fillRect(120,240,400,70);
            GameUtils.drawWord(g,"游戏暂停 - 按空格继续",GameUtils.COLOR_PAUSE_TEXT,35,150,290);
        }
        //失败
        if (state == 3){
            g.fillRect(120,240,400,70);
            GameUtils.drawWord(g,"游戏失败! 按空格重新开始",GameUtils.COLOR_FAIL_TEXT,35,150,290);
        }
        //通关
        if (state == 4){
            g.fillRect(120,240,400,70);
            if (GameUtils.level == 5){
                GameUtils.drawWord(g,"无尽模式! 按空格重新开始",GameUtils.COLOR_ENDLESS_TEXT,35,150,290);
            } else if (GameUtils.level == GameUtils.LEVEL_TARGETS.length){
                GameUtils.drawWord(g,"恭喜! 全部关卡通关!",GameUtils.COLOR_WIN_TEXT,35,150,290);
            }else {
                GameUtils.drawWord(g,"关卡完成! 按空格进入下一关",GameUtils.COLOR_WIN_TEXT,35,150,290);
            }
        }
    }

    //游戏重置
    void resetGame(){
        //关闭当前窗口
        this.dispose();
        //开启一个新窗口
        String[] args = {};
        main(args);
    }

    public static void main(String[] args){
        GameWin gameWin = new GameWin();
        gameWin.launch();
    }
}